#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
批量修复ForeignKey字段缺少on_delete参数的问题
"""
import os
import re
import glob

def fix_foreign_key_file(file_path):
    """修复单个文件中的ForeignKey字段"""
    try:
        # 跳过不需要修复的文件
        if any(skip in file_path for skip in ['__pycache__', '.pyc', '.git', 'migrations', 'fix_']):
            return False
            
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        original_content = content
        
        # 修复 ForeignKey 字段，添加 on_delete=models.CASCADE
        # 模式1: models.ForeignKey(Model, ...)
        content = re.sub(
            r'models\.ForeignKey\(([^,\)]+)(?!.*on_delete)',
            r'models.ForeignKey(\1, on_delete=models.CASCADE',
            content
        )
        
        # 修复已有参数但缺少 on_delete 的情况
        # 模式2: models.ForeignKey(Model, verbose_name=..., ...)
        pattern = r'models\.ForeignKey\(([^,\)]+),\s*([^)]*?)\)(?![^}]*on_delete)'
        
        def add_on_delete(match):
            model = match.group(1)
            params = match.group(2).strip()
            
            # 如果已经有 on_delete，跳过
            if 'on_delete' in params:
                return match.group(0)
            
            # 添加 on_delete 参数
            if params:
                return f'models.ForeignKey({model}, on_delete=models.CASCADE, {params})'
            else:
                return f'models.ForeignKey({model}, on_delete=models.CASCADE)'
        
        # 使用更精确的正则表达式
        foreign_key_pattern = r'models\.ForeignKey\(([^,\)]+)(?:,\s*([^)]*?))?\)(?![^}]*on_delete)'
        content = re.sub(foreign_key_pattern, add_on_delete, content)
        
        # 修复一些特殊情况
        # User 模型通常使用 CASCADE
        content = re.sub(
            r'models\.ForeignKey\(User,\s*on_delete=models\.CASCADE,\s*on_delete=models\.CASCADE',
            'models.ForeignKey(User, on_delete=models.CASCADE',
            content
        )
        
        # 修复重复的 on_delete
        content = re.sub(
            r'on_delete=models\.CASCADE,\s*on_delete=models\.CASCADE',
            'on_delete=models.CASCADE',
            content
        )
        
        # 只有在内容发生变化时才写入文件
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"✓ 修复完成: {file_path}")
            return True
        else:
            return False
            
    except Exception as e:
        print(f"✗ 修复失败 {file_path}: {e}")
        return False

def main():
    """主函数"""
    base_dir = os.path.dirname(os.path.abspath(__file__))
    
    print("开始批量修复ForeignKey字段问题...")
    print("=" * 50)
    
    # 获取所有Python文件
    python_files = []
    for root, dirs, files in os.walk(base_dir):
        # 跳过某些目录
        dirs[:] = [d for d in dirs if d not in ['__pycache__', '.git', 'static', 'media']]
        
        for file in files:
            if file.endswith('.py') and not file.startswith('fix_'):
                file_path = os.path.join(root, file)
                # 检查文件是否包含ForeignKey
                try:
                    with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                        content = f.read()
                        if 'models.ForeignKey' in content and 'on_delete' not in content:
                            python_files.append(file_path)
                except:
                    pass
    
    print(f"找到 {len(python_files)} 个需要修复的文件")
    
    # 修复文件
    fixed_count = 0
    failed_count = 0
    
    for file_path in python_files:
        try:
            if fix_foreign_key_file(file_path):
                fixed_count += 1
        except Exception as e:
            print(f"✗ 处理文件失败 {file_path}: {e}")
            failed_count += 1
    
    print("=" * 50)
    print(f"修复完成！")
    print(f"✓ 成功修复: {fixed_count} 个文件")
    print(f"✗ 失败: {failed_count} 个文件")
    print(f"总计处理: {len(python_files)} 个文件")

if __name__ == "__main__":
    main() 